package com.yonxao.demo.crud.annotation.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.yonxao.demo.crud.core.IEntityEnum;

import java.io.IOException;

/**
 * 实体枚举属性的反序列化方法
 *
 * @author yonxao
 * @date 2021/3/20
 */
public class EntityEnumDeserializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    private Class<?> targetClass;

    public EntityEnumDeserializer() {
    }

    public EntityEnumDeserializer(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        Number value = jsonParser.getNumberValue();
        Object[] enumConstants = targetClass.getEnumConstants();
        for (Object enumConstant : enumConstants) {
            if (((IEntityEnum) enumConstant).getCode().equals(value.byteValue())) {
                return enumConstant;
            }
        }
        return null;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        return new EntityEnumDeserializer(deserializationContext.getContextualType().getRawClass());
    }
}